<template>
  <div style="position: relative; height: 100%" ref="mapContainer">
    <!-- 地图加载 -->
    <div
      id="cesiumContainer"
      ref="cesiumContainer"
      style="width: 100%; height: 100vh"
    ></div>
    <v-card class="nav" elevation="12" width="500">
      <v-navigation-drawer
        floating
        permanent
        style="background: transparent; width: 500px"
      >
        <v-list style="background: transparent" dense rounded class="d-flex">
          <v-list-item style="background: rgba(255, 255, 255, 0.9)" link>
            <!-- 搜索 -->
            <input
              style="border: none; outline: none; width: 100%"
              placeholder="请输入查询地点"
              v-model="search"
              clearable
              @input="debounceSearch"
            />
            <v-icon small v-show="search" @click="search = ''">
              mdi-close-circle-outline
            </v-icon>
          </v-list-item>
        </v-list>
      </v-navigation-drawer>
    </v-card>
    <!-- 搜搜出信息列表 -->
    <div class="list" v-if="search">
      <div class="list-conent">
        <div
          class="list-item"
          :class="{ 'item-item1': item.id == itemRow.id }"
          v-for="(item, index) in pois"
          :key="index"
          @click="clickSearch(item.location, item)"
        >
          <div class="item-name">{{ item.name }}</div>
          <div class="item-type">{{ item.type }}</div>
          <div class="item-address">{{ item.address }}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
var viewer, handler;
// event maker
//
import axios from "axios";
// 截留函数
const delay = (() => {
  let timer = null;
  return (callback, ms) => {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();
export default {
  data() {
    return {
      pois: [], // 数据数组
      search: "",
      dates: [],
      date: "",
      dialogForm: false,
      dialog: false,
      items: [{ title: "按项目搜索", icon: "mdi-view-dashboard" }],
      form: {
        matterName: "",
        matterCode: "",
        startBudget: "",
        endBudget: "",
        planOnDateStart: "",
        planOnDateEnd: "",
        planFinishDateStart: "",
        planFinishDateEnd: "",
        matterType: "",
        startDate: "",
        endDate: "",
      },
      info: {
        matterCode: "",
        matterName: "",
        companyName: "",
        budget: "",
        currentProgress: "",
      },
      itemRow: {},
      useValue: [],
    };
  },
  mounted() {
    // 高度
    // this.$refs.cesiumContainer.style.height =
    //   this.$refs.mapContainer.offsetHeight + "px";

    window.addEventListener("message", (event) => {
      const { data } = event;
      console.log(data, "data111");
      if (data.event) {
        console.log(data, "子打印");
        this[data.event](data.params);
      }
      if (data.params && data.params.value) {
        this.useValue = data.params.value;
      }
    });

    window.startupCalled = true;
    this.init();
  },
  methods: {
    // 点击搜索信息给地图添加点
    clickSearch(location, item) {
      let arr = location.split(",");
      this.itemRow = item;
      window.parent.postMessage(
        {
          // 参数是对象
          ROW: item,
        },
        "*"
      );
      // 清除所有点
      viewer.entities.removeAll();
      // 添加点
      viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(arr[0] - 0.006, arr[1] - 0.002),
        billboard: {
          image: require("../assets/dw.png"),
          pixelOffset: new Cesium.Cartesian2(0, -10),
          scale: 0.1,
          width: 200,
          height: 200,
        },
      });

      viewer.camera.flyTo({
        //定位过去
        destination: Cesium.Cartesian3.fromDegrees(
          arr[0],
          parseFloat(arr[1]) - 0.03,
          9000
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0.0),
          pitch: Cesium.Math.toRadians(-90),
        },
      });
    },
    // 搜索节流
    debounceSearch() {
      delay(() => {
        this.srarch();
      }, 300);
    },
    // 搜索
    srarch() {
      if (!this.search) return;
      axios
        .get(
          `https://restapi.amap.com/v3/place/text?keywords=${this.search}&city=沈阳&offset=20&page=1&key=48755dfe1035054daf637e354221d76b`
        )
        .then((res) => {
          this.pois = res.data.pois;
        });
    },
    close() {
      for (let i in this.form) {
        this.form[i] = "";
      }
    },
    submit() {
      console.log(this.form, "from");
      window.parent.postMessage(
        {
          params: this.form,
        },
        "*"
      );
      this.dialogForm = false;
      this.close();
    },
    startDateChange(date) {
      this.form.planOnDateStart = date[0] + " 00:00:00";
      this.form.planOnDateEnd = date[1] + " 23:59:59";
      this.form.startDate = date[0] + "~" + date[1];
    },
    endDateChange(date) {
      this.form.planFinishDateStart = date[0] + " 00:00:00";
      this.form.planFinishDateEnd = date[1] + " 23:59:59";
      this.form.endDate = date[0] + "~" + date[1];
    },
    addMakerArr(arr) {
      viewer.entities.removeAll();
      arr.forEach((p) => {
        console.log(p, "p");
        this.addMaker(p);
      });
    },
    addMaker(p) {
      viewer.entities.add({
        label: {
          text: p.matterName,
          font: "400 12px Helvetica",
          pixelOffset: new Cesium.Cartesian2(0, -70),
          showBackground: true,
          backgroundColor: new Cesium.Color(0 / 255, 0 / 255, 0 / 255, 1.0),
        },
        position: Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude),
        billboard: {
          image: require("../assets/caremra.png"),
          pixelOffset: new Cesium.Cartesian2(0, 0),
          scale: 0.1,
          width: 210,
          height: 588,
        },
        monitoItems: p,
      });

      viewer.camera.flyTo({
        //定位过去
        destination: Cesium.Cartesian3.fromDegrees(
          p.longitude,
          parseFloat(p.latitude) - 0.03,
          1800
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0.0),
          pitch: Cesium.Math.toRadians(-25.2),
        },
      });
    },
    // 初始化加载地图
    init() {
      viewer = new Cesium.Viewer("cesiumContainer", {
        infoBox: false,
        isSct: false,
      });
      viewer.scene.globe.baseColor = Cesium.Color.TRANSPARENT;
      viewer.scene.backgroundColor = Cesium.Color.TRANSPARENT;
      viewer._cesiumWidget._creditContainer.style.display = "none";

      var imageryLayers = viewer.imageryLayers;
      var provider = new Cesium.UrlTemplateImageryProvider({
        url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}",
      });
      var imagery = imageryLayers.addImageryProvider(provider);
      imagery.alpha = 1.0;
      let arr = [123.464675, 41.712768];
      if (this.useValue.length) {
        arr = this.useValue;
      }
      viewer.scene.camera.flyTo({
        destination: new Cesium.Cartesian3.fromDegrees(
          arr[0],
          parseFloat(arr[1]) - 0.03,
          9000
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0.0),
          pitch: Cesium.Math.toRadians(-90), //从上往下看为-90
        },
      });

      handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      // 点击标点触发
      handler.setInputAction((e) => {
        var pick = viewer.scene.pick(e.position);
        console.log(pick, "pick");
        window.parent.postMessage(
          {
            // 参数是对象
            ROW: this.itemRow,
          },
          "*"
        );
        if (!pick || !pick.id._monitoItems) return;
        this.info = pick.id._monitoItems;
        // 调用弹窗方法
        this.dialog = true;
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    getlonLat(e) {
      var ellipsoid = viewer.scene.globe.ellipsoid;
      var cartesian = viewer.camera.pickEllipsoid(e.position, ellipsoid);
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      var lng = Cesium.Math.toDegrees(cartographic.longitude);
      var lat = Cesium.Math.toDegrees(cartographic.latitude);
      return { lng, lat };
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.cesium-viewer-navigationContainer,
.sm-compass-outer-ring {
  display: none;
}
.nav {
  position: absolute;
  z-index: 2022;
  top: 0;
  left: 0;
  background: transparent;
  box-shadow: 0 0 0 !important;
}
.list {
  position: absolute;
  top: 49px;
  width: 500px;
  max-height: 500px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  margin: 0 10px;
  box-sizing: border-box;
  overflow: hidden;
}
.list-conent {
  width: 100%;
  max-height: 500px;
  overflow-y: auto;
}
.list-item {
  box-sizing: border-box;
  padding: 8px 15px;
  border-bottom: 1px solid #eee;
  line-height: 20px;
}
.item-item1 {
  background-color: rgba(248, 248, 255, 0.8);
}
.item-name {
  font-size: 14px;
  font-weight: 600;
}
.item-type {
  font-size: 14px;
  font-weight: 400;
}
.item-address {
  font-size: 12px;
  font-weight: 400;
  color: #aaa;
}
</style>
